function findBreakPoint (text, width, context) {
    var min = 0;
    var max = text.length - 1;
     
    while (min <= max) {
        var middle = Math.floor((min + max) / 2);
        var middleWidth = context.measureText(text.substr(0, middle)).width;
        var oneCharWiderThanMiddleWidth = context.measureText(text.substr(0, middle + 1)).width;
        if (middleWidth <= width && oneCharWiderThanMiddleWidth > width) {
            return middle;
        }
        if (middleWidth < width) {
            min = middle + 1;
        } else {
            max = middle - 1;
        }
    }
     
    return -1;
}
function breakLinesForCanvas (TextObj,context) {
	var text=TextObj.text;
	var width=TextObj.width;
	var font=TextObj.weight+' '+TextObj.size+' '+TextObj.family;
   /* var canvas = document.getElementById('textcanvas');
    var context = canvas.getContext('2d');*/
    var result = [];
    var breakPoint = 0;
     
    if (font) {
        context.font = font;
    }
     context.font = font;
     context.fillStyle = TextObj.color;
     context.textAlign = TextObj.center;
     
    while ((breakPoint = findBreakPoint(text, width, context)) !== -1) {
        result.push(text.substr(0, breakPoint));
        text = text.substr(breakPoint);
    }
     
    if (text) {
        result.push(text);
    }
     
    return result;
}

function drawlinetext(TextObj,fn){	
	var canvas=document.createElement('canvas');	
	canvas.width=TextObj.width;
	canvas.height=TextObj.height;
	var context = canvas.getContext('2d');
	var result = breakLinesForCanvas(TextObj,context);	
	var context_x=0;
	if(TextObj.center=="center"){
		context_x=TextObj.width/2;
	}else if(TextObj.center=="right"){
		context_x=TextObj.width;
	}else{
	context_x=0;	
	}
	
	
	result.forEach(function (line, index) {
	  context.fillText(line, context_x, TextObj.lineHeight * (index+1));
	});
	//console.log(canvas.toDataURL());
	fn(canvas);
}
